package com.aurora.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.aurora.common.constant.AuthServerConstant;
import com.aurora.common.exception.ErrorCodeException;
import com.aurora.common.utils.R;
import com.aurora.common.vo.MemberResponseVo;
import com.aurora.gulimall.auth.feign.MemberFeignService;
import com.aurora.gulimall.auth.feign.ThirdPartyFeignService;
import com.aurora.gulimall.auth.vo.UserLoginVo;
import com.aurora.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class LoginController {
    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**验证码服务-生成、保存redis
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //TODO 2、接口防刷

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        if(!StringUtils.isEmpty(redisCode)){
            long lastSendTime = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - lastSendTime < 60000){
                //60秒内不能再发验证码
                return R.error(ErrorCodeException.SMS_CODE_EXCEPTION.getCode(),ErrorCodeException.SMS_CODE_EXCEPTION.getErrorMessage());
            }
        }
        //存在的问题
        //1、验证码校验;重复发送。redis
        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone,code.split("_")[0]);
        return R.ok();
    }

    /**
     * 重定向携带数据：将数据放到session中。只要跳到下一个页面取出这个数据后，session里面的数据就会删除掉。
     * TODO 分布式session取数据会存在问题
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){//校验出错，转发到注册页
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField,
                            FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //用户注册-》/regist->转发/reg.html（mywebconfig中默认都是get请求）
//            return "forward:/reg.html";//视图解析器不拼串
//            return  "reg";//视图解析器会进行拼串
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //1、校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(redisCode)){
            redisCode = redisCode.split("_")[0];
            if(code.equals(redisCode)){
                //验证码通过,删除验证码  令牌机制：用过的验证码会失效应及时删除
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //调用远程服务注册
                R r = memberFeignService.regist(vo);
                if(r.getCode() == 0){
                    //远程调用成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String,String> errors = new HashMap<>();
                    errors.put("errors",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0){
            MemberResponseVo data = login.getData(new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }
}
